package com.leo.leetcode.s100;

/**
 *
 * @author xuexiaolei
 * @version 2017年11月16日
 */
public class T05LongestPalindromicSubstring2 {
    public static String longestPalindrome(String s) {
        if (s == null || "".equals(s)){ return "";}
        char[] chars = s.toCharArray();
        int ansStart=0,ansEnd=0;
        int start,end;

        for (int i = 0; i < s.length(); i++) {
            //中间没有单个字符的情况
            start=i;end=i+1;
            while (start>=0 && end<s.length() && chars[start]==chars[end]){
                start--;
                end++;
            }
            if ((end-start-2)>(ansEnd-ansStart)){ ansEnd=--end; ansStart=++start; }
            //中间是单个字符的情况
            start=i-1;end=i+1;
            while (start>=0 && end<s.length() && chars[start]==chars[end]){
                start--;
                end++;
            }
            if ((end-start-2)>(ansEnd-ansStart)){ ansEnd=--end; ansStart=++start; }
        }


        //不要引入一个新的对象了！
//        StringBuffer sb = new StringBuffer();
//        for (int i = ansStart; i <= ansEnd ; i++) {
//            sb.append(chars[i]);
//        }
//        return sb.toString();
        return s.substring(ansStart, ansEnd+1);
    }

    public static void main(String[] args) {
        System.out.println(longestPalindrome("babad"));
        System.out.println(longestPalindrome("cbbd"));
        System.out.println(longestPalindrome("a"));
        System.out.println(longestPalindrome("aba"));
        System.out.println(longestPalindrome(""));
        System.out.println(longestPalindrome("ccc"));
        System.out.println(longestPalindrome("cccc"));
    }
}
